<template >
  <div class="app-bg flex" id="app-oweinfo" style="height:100%;">
    <div class="flex-row " style="background: #108ADD;justify-content: center;padding: 20px;">
      <img src="../../assets/jiaofeixiangq.png" alt="" class="img-responsive" style="margin-right: 20px;margin-left: 30px;">
      <div class="flex " style="flex: 1;justify-content: space-between;color:#FFF;">
        <span>户号 {{userinfo.f_userinfo_id}}</span>
        <span>姓名 {{userinfo.f_user_name}}</span>
        <span >余额 {{balance.f_balance}}</span>
      </div>
    </div>


    <span style="padding: 8px;">欠费记录：
      <span style="color:red">总欠费：{{payfeesum}}</span>
   </span>
    <span v-for='row in price'  >
      <span>{{row.f_price_name}}（{{row.f_ratio}}） :{{row.f_describe}}</span>
    </span>
  <div style="flex: 1;overflow: scroll;">
    <div v-for='row in owe' class="app-panel">
      <accordion :one-at-atime="checked" type="info">
        <panel :is-open="false">
          <div slot="header" class="row">
            <span class="col-xs-3" style="color: red;">欠费:</span>
            <span class="col-xs-3" style="color: red;">{{row.f_oughtfee}}</span>
            <span class="col-xs-3">所属月份</span>
            <span class="col-xs-2">{{row.f_hand_date}}</span>
            <span class="col-xs-1 glyphicon glyphicon-menu-right"></span>
          </div>
          <div >
            <div class="row">
              <span class="col-xs-3">上指数</span><span class="col-xs-3">{{row.f_last_tablebase}}</span>
              <span class="col-xs-3">本指数</span><span class="col-xs-3">{{row.f_tablebase}}</span>
            </div>
            <div class="row">
              <span class="col-xs-3">水量</span><span class="col-xs-3">{{row.f_oughtamount}}</span>
              <span class="col-xs-3">金额</span><span class="col-xs-3">{{row.f_oughtfee}}</span>
            </div>
          </div>
        </panel>
      </accordion>
    </div>
  </div>


    <div class="flex" style="background: #FFF;align-items: center;padding-top: 10px;margin-top: 10px;">
      <span style="padding: 8px;border-bottom: 1px solid #e0e0e0;width: 100%;text-align: center;">收款</span>
      <input disabled v-model='payfeesum' style="padding: 8px;border: 1px solid #E0E0E0;border-radius: 5px;text-align: center;margin:15px;"
      placeholder="请输入收款金额">
      <div class="app-btn">
        <button type="button" name="button" class="btn btn-primary"  @click="back()" >返回</button>
        <button type="button" name="button" class="btn btn-primary" @click="pay()">缴费</button>
        <button type="button" name="button" class="btn btn-primary" @click="print()">票据补打</button>
      </div>
    </div>

  </div>
</template>

<script>
import co from 'co'
import config from '../../../src/components/config'
import appData from '../../../src/components/appData'
import * as Util from '../Util'
let oweinfo = function * (self,flag){
  yield self.$post(config.resultUrl +'rs/logic/oweinfo', {data: self.userinfo},
  // yield self.$post('rs/logic/oweinfo', {data: self.userinfo},
{resolveMsg: null, rejectMsg: null})
.then((res)=>{
  console.log(JSON.stringify(res.data))
  if (res.data.stairprice === 0) {
    self.$showMessage('该用户水价有问题，不能进行缴费，待数据上传之后，用户可在营业厅进行缴费')
    self.$goto('meter-userinfsearch', {rowdata: self.userinfo})
  } else {
    if (flag) {
      self.owe = res.data.data
      self.balance = res.data.f_balance
      if (!self.flag) {
        self.benciowe = {
          f_hand_date:Util.toStandardDateString(),
          f_oughtfee:res.data.owe,
          f_last_tablebase:self.userinfo.f_last_tablebase,
          f_tablebase:self.userinfo.f_tablebase,
          f_oughtamount: self.userinfo.f_oughtamount
        }
        self.owe.unshift(self.benciowe)
      }

      let sum =0
      let water = 0
      for (var i = 0; i < self.owe.length; i++) {
        sum = sum + self.owe[i].f_oughtfee
        water = water + parseFloat(self.owe[i].f_oughtamount)
      }
      self.payfeesum = sum.toFixed(2)
      self.paywatersum = water
    } else {
      self.balance = res.data.f_balance
      self.owe = res.data.data

      let sum =0
      for (var i = 0; i < self.owe.length; i++) {
        sum = sum + self.owe[i].f_oughtfee
      }
      self.payfeesum = sum.toFixed(2)

      self.$showMessage('票据打印成功',['confirm'])
      .then((rescon)=>{
        if (rescon === 'confirm') {
            self.$goto('meter-userinfsearch', {rowdata: self.userinfo})
        }
      })
    }
  }

})
.catch((ret)=>{
  self.$showMessage('请求欠费数据失败,检查网络是否畅通，并重新请求数据')
      self.$goto('meter-userinfsearch', {rowdata: this.userinfo})
})

}
let pay = function * (self,data) {
yield self.$post(config.resultUrl +'rs/logic/pay', {data:data},
// yield self.$post('rs/logic/pay', {data:data},
{resolveMsg: null, rejectMsg: null})
  .then((res)=>{
    self.$showMessage('是否打印收费单',['confirm'])
    .then((res)=>{
      if (res === 'confirm') {
        //获取详细单价
        let stairprice_id = `(`
        for (var t = 0; t < self.price.length; t++) {
          if (t < self.price.length-1) {
            stairprice_id = stairprice_id + `${self.price[t].sid},`
          } else if (t === self.price.length-1 ) {
            stairprice_id = stairprice_id + `${self.price[t].sid}`
          }

        }
        stairprice_id += `)`
        let condi = `1=1 and f_stairprice_id != '' and f_stairprice_id in ${stairprice_id}`
        self.$post(config.resultUrl +'rs/sql/singleTable_Close', {data:{condition: condi,items: `SUM(f_price) price,f_stairprice_id`,tablename: 't_detailprice',orderitem:'f_stairprice_id',groupitem: 'f_stairprice_id'}},
        // self.$post('rs/sql/singleTable_Close', {data:{condition: condi,items: `SUM(f_price) price,f_stairprice_id`,tablename: 't_detailprice',orderitem:'f_stairprice_id',groupitem: 'f_stairprice_id'}},
        {resolveMsg: null, rejectMsg: null})
        .then((res)=>{
          self.detailprice = res.data
          //组织打印数据
          //循环出多套水价的类别和水价，水费和水量
          // p 水价，w 水量，f 水费
          //json 对象 d,ds
          let p = 0
          let w = 0
          let f = 0
          let d = {}
          let ds=[]
          for (var i = 0; i < self.price.length; i++) {
            console.log(i)
            console.log(self.price[i].sid)
            p=0
            w=0
            f=0
            d={}
            //水价
            console.log('开始相加单价');
            for (var j = 0; j < res.data.length; j++) {
              console.log(j)
              console.log(res.data[j].f_stairprice_id)

              if (self.price[i].sid === res.data[j].f_stairprice_id) {
                console.log(res.data[j].price)
                p = res.data[j].price
              }
            }
            w = self.owe[0].f_oughtamount * self.price[i].f_ratio//水量
            f = w*p//水费
            d.type= self.price[i].f_price_name
            d.price = p
            d.w = w
            d.f = f.toFixed(2)
            ds.push(d)
            }
          let das = ''
          for (var g = 0; g < ds.length; g++) {
            for (var key in ds[g]) {
              if (key === 'type') {
                das = das + `类别: ${ds[g].type}  `
              } else if (key === 'price') {
                das = das + `水价: ${ds[g].price}\n`
              } else if (key === 'w') {
                das = das + `水量${ds[g].w}吨  `
              } else if (key === 'f') {
                das = das + `水费${ds[g].f}元\n`
              }
            }
          }
          console.log(das);

          let qf = ''
          for (var k = 1; k < self.owe.length; k++) {
                qf = qf + `欠费时间 ${self.owe[k].f_hand_date}\n`+
                `欠水量 ${self.owe[k].f_oughtamount}吨 ${self.owe[k].f_oughtfee} 元\n`
          }
            console.log(qf);
          //${Util.toStandardDateString()}
          let lasthanddate = self.hand.length>0?self.hand[0].f_hand_date:Util.toStandardDateString()
          self.printdata  = `      博能燃气有限公司\n`+
                            `          水费收费单\n`+
                            `   用户编号:${self.userinfo.f_userinfo_id}抄表员:${self.userinfo.f_inputtor}\n\n` +
                            `用户名称：${self.userinfo.f_user_name}\n`+
                            `用户地址：${self.userinfo.f_address}\n`+
                            `上期抄表日：${lasthanddate}\n` +
                            `本期抄表日：${Util.toStandardDateString()}\n`+
                            `上期底数：${self.owe[0].f_last_tablebase}\n`+
                            `本期底数：${self.owe[0].f_tablebase}\n`+
                            `本期水量：${self.owe[0].f_oughtamount}\n`+
                            `本期水费：${self.owe[0].f_oughtfee}\n`+
                             das+
                             `********************************\n`+
                             qf +
                             `********************************\n`+
                             `应收： ${self.payfeesum}                                       `
          console.log(self.printdata)

          self.backstate = true
          self.paystate = true
          self.payfeesum = 0
          self.paywatersum = 0
          self.print()
        })
        .catch((ret)=>{
          self.$showMessage('获取具体水价信息失败,可在票据补打页面进行票据补打')
        })
      }
    })
  })
  .catch ((ret)=>{
    self.backstate = false
   self.$showMessage('缴费出错，检查网络，重新进行缴费')
  })

}

export default {
  title: '缴费页面',
  props: ['userinfo','flag'],
  data(){
    return {
      owe:[],
      benciowe:'',
      balance:0,
      paydata: '',
      backstate: false,
      payfeesum: 0,
      paywatersum: 0,
      paystate: true,
      //图片数据
      content: '',
      price:[],
      detailprice: [],
      hand: [],
      //打印数据
      printdata: ''
    }
  },
  ready(){
    //获取价格比率和描述
    let condition = `1=1 and u.f_user_id= '${this.userinfo.f_user_id}' and u.f_state = 1 and u.f_price_id = s.f_userprice_id and s.f_state = '有效'`
    let items = `u.*,s.id sid`
    let tablename = `t_userprice u, t_stairprice s`
    this.$post(config.resultUrl +'rs/sql/singleTable_OrderBy', {data:{condition: condition,items: items,tablename: tablename,orderitem:'u.f_user_id'}},
    // this.$post('rs/sql/singleTable_OrderBy', {data:{condition: condition,items: items,tablename: tablename,orderitem:'u.f_user_id'}},
    {resolveMsg: null, rejectMsg: null})
    .then((res)=>{
      this.price = res.data
    })
    .catch((ret)=>{
      this.$showMessage('获取水价信息失败')
    })

    //获取上次抄表时间
    let con = `1=1 and  id =(select max(id) from t_handplan where f_meter_state = '已抄表' and f_whether_pay = '是' and f_user_id = '${this.userinfo.f_user_id}')`
    this.$post(config.resultUrl +'rs/sql/singleTable_OrderBy', {data:{condition: con ,items: 'f_hand_date',tablename: 't_handplan',orderitem:'f_hand_date'}},
      // this.$post('rs/sql/singleTable_OrderBy', {data:{condition: con ,items: 'f_hand_date',tablename: 't_handplan',orderitem:'f_hand_date'}},
    {resolveMsg: null, rejectMsg: null})
    .then((res)=>{
      this.hand = res.data
    })
    .catch((ret)=>{
      this.$showMessage('获取上次抄表日期失败')
    })
    this.search(true)
  },
  methods: {
    print () {
      if (this.printdata !== '') {
        let result =  HostApp.print(this.printdata)
        if (result.code === 200) {
          this.search(false)
        } else if (result.code === 501) {
          this.$showMessage('票据打印失败，蓝牙连接不可用，检查蓝牙')
        } else {
          this.$showMessage('票据打印失败，检查设备是否打开')
        }
      } else {
        this.$showMessage('没有缴费，不能进行票据补打')
      }


    },
    back(){
      if (this.backstate) {
        this.$goto('meter-userinfsearch', {rowdata: this.userinfo})
      } else {
        this.$back()
      }
    },
    search(flag){
      let gen = oweinfo(this,flag)
      return co(gen)
    },
    pay() {
      let sum = 0
      for (var i = 0; i < this.owe.length; i++) {
        sum = sum + this.owe[i].f_oughtfee.toFixed(2)
      }
      if (this.payfeesum < sum) {
        this.$showMessage('缴费金额必须大于欠费总和')
      } else {
          if (this.owe.length >0) {
            // 获取图片数据
            if (this.paystate) {
              this.paystate = false
              // let result = HostApp.context(this.userinfo.f_meter_path)
              // if (result.code === 200) {
              //   this.content = result.result
              // } else {
              // HostApp.alert('提取图片数据失败')
              // return
              // }
              //组织缴费数据
              this.paydata = Object.assign ({},this.paydata,this.userinfo)
              this.paydata.userfile = {
                f_user_id: this.paydata.f_user_id,
                f_meter_base: this.paydata.f_tablebase,
                version: this.userinfo.version
              }
              this.paydata.f_oughtfee = this.owe[0].f_oughtfee
              this.paydata.f_real_prewater = this.paywatersum
              this.paydata.f_haircut_water = 0
              this.paydata.f_surplus_water = 0
              this.paydata.f_inputtor  = appData.loginUser.logininfo[0].f_bieming
              this.paydata.f_input_date = Util.toStandardDateString()
              this.paydata.f_end_date = Util.toStandardDateString()
              this.paydata.f_meter_state = '已抄表'
              this.paydata.f_whether_pay = '是'
              this.paydata.f_operator = appData.loginUser.logininfo[0].f_bieming
              this.paydata.f_upload = '已上传'
              this.paydata.f_download = '已处理'
              this.paydata.version = this.balance.version
              this.paydata.f_balance = this.balance.f_balance
              this.paydata.f_last_tablebase = this.owe[0].f_last_tablebase
              this.paydata.f_meter_base = this.owe[0].f_last_tablebase
              this.paydata.money = this.payfeesum
              this.paydata.f_sumoughtfee = this.payfeesum
              this.paydata.flag = true
              if (this.flag) {
                //不录入
                this.paydata.sign = 0
              } else {
                //录入
                this.paydata.sign = 1
              }
            //  this.paydata.content = this.content
            //  this.paydata.f_meter_path = this.paydata.f_meter_path.substring(37,this.paydata.f_meter_path.indexOf('?'))
              let gen = pay(this, this.paydata)
              return co(gen)
            } else {
              this.$showMessage('你已经提交过支付请求，不要进行重复提交')
            }


          } else {
            this.$showMessage('没有欠费，不能进行缴费')
          }

      }

    }
  }
}
</script>

<style scoped>
  #app-oweinfo, #app-oweinfo div {
    height: auto;
  }
  .app-panel .panel-default > .panel-heading {
    background: #FFF;
  }
  .app-panel {
    margin-top: 10px;
  }
  .app-panel .panel-group {
    margin: 0px;

  }
</style>
